﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace 账号管理
{
    public partial class FormAdd : Form
    {
        private bool Add = true;
        public FormAdd()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            IDatabase db = DatabaseFactory.CreateDatabase("sqlite");
            if (txtAccount.Text.IsNullOrEmpty())
            {
                MessageBox.Show("请输入账号！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (Add)
            {
                db.ExecuteNonQuery("insert into 账号(主题,账号,密码,网站,备注) values (@title,@acc,@pwd,@url,@remark)",
                    new
                    {
                        title = XEncrypt.DES_Encrypt(txtName.Text),
                        acc = XEncrypt.DES_Encrypt(txtAccount.Text),
                        pwd = txtPwd.Text.IsNullOrEmpty() ? string.Empty : XEncrypt.DES_Encrypt(txtPwd.Text),
                        url = txtUrl.Text,
                        remark = txtMemo.Text,
                    });
            }
            else
            {
                db.ExecuteNonQuery("update 账号 set 账号=@acc,密码=@pwd,网站=@url,备注=@remark,主题=@title where id=@id",
                    new
                    {
                        id = _DataSource.Id,
                        title = XEncrypt.DES_Encrypt(txtName.Text),
                        acc = XEncrypt.DES_Encrypt(txtAccount.Text),
                        pwd = txtPwd.Text.IsNullOrEmpty() ? string.Empty : XEncrypt.DES_Encrypt(txtPwd.Text),
                        url = txtUrl.Text,
                        remark = txtMemo.Text,
                    });
            }
            this.FindForm().DialogResult = DialogResult.OK;
            this.Close();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        AccountData _DataSource = null;

        internal AccountData Source
        {
            get
            {
                return new AccountData
                {
                    Title = txtName.Text,
                    Acc = txtAccount.Text,
                    Url = txtUrl.Text,
                    Pwd = txtPwd.Text,
                    Remark = txtMemo.Text,
                };
            }
        }
        internal void SetSource(AccountData acc)
        {
            if (acc == null) acc = new AccountData();

            Add = false;

            bsMain.DataSource = _DataSource = acc;
            bsMain.ResetBindings(false);
        }
    }
}
